package com.zjlp.im.netty.handler;

import com.alibaba.fastjson.JSONObject;
import com.zjlp.im.netty.wrapper.MsgWrapper;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.apache.commons.lang3.StringUtils;

import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * Created by joker on 2016/12/26.
 */
public class ChatMsgHandler extends ChannelInboundHandlerAdapter {
    //用户
    private String user;
    //聊天对象
    private String client;

    public ChatMsgHandler(String user, String client) {
        this.user = user;
        this.client = client;
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt.toString().equals("chatEvent")) {
            //扑捉用户输入
            while (true) {
                BufferedReader strin = new BufferedReader(new InputStreamReader(System.in));
                System.out.print("请输入聊天消息：");
                String str = strin.readLine();
                if (!StringUtils.isBlank(str)) {
                    MsgWrapper msgWrapper = this.wrapperChatMsgInfo(str);
                    ByteBuf response = ByteBufUtil.writeUtf8(ByteBufAllocator.DEFAULT, JSONObject.toJSONString(msgWrapper));
                    ctx.writeAndFlush(response);
                    System.out.println("给服务端发完消息了！！！");
                    break;
                }
            }
        } else {
            System.out.println("无法处理的用户事件");
        }
    }

    /**
     *
     * @param content
     * @return
     */
    private MsgWrapper wrapperChatMsgInfo(String content) {
        MsgWrapper msgWrapper = new MsgWrapper();
        msgWrapper.setType(3);
        msgWrapper.setUser(user);
        msgWrapper.setTo(client);
        msgWrapper.setContent(content);
        return msgWrapper;
    }
}
